@echo off
setlocal

:: --- Configuration ---
set "JAR_PATH=admin\target\aibox-pro.jar"
set "LOG_FILE=app.log"
set "PID_FILE=app.pid"
set "WINDOW_TITLE=aibox-pro-service"
:: ---------------------

echo Starting the application...

if not exist "%JAR_PATH%" (
    echo ERROR: JAR file not found at %JAR_PATH%
    exit /b 1
)

:: Check if already running by checking for the PID file and if the process exists
if exist "%PID_FILE%" (
    set /p PID=<"%PID_FILE%"
    tasklist /FI "PID eq !PID!" 2>NUL | find /I "!PID!" >NUL
    if "!errorlevel!"=="0" (
        echo WARN: Application is already running with PID !PID!.
        exit /b 0
    ) else (
        echo WARN: Stale PID file found. Deleting it.
        del "%PID_FILE%"
    )
)


:: Start the application in a new background window without focus with prod profile
start "%WINDOW_TITLE%" /B javaw -jar "%JAR_PATH%" --spring.profiles.active=prod >> "%LOG_FILE%" 2>&1

:: Find the PID and save it. We wait a few seconds for the process to initialize.
echo Waiting for application to start to get PID...
timeout /t 3 /nobreak >nul

for /f "tokens=2" %%i in ('tasklist /v /fi "imagename eq javaw.exe" /fi "windowtitle eq %WINDOW_TITLE%*" /fo csv /nh') do (
    set "PID=%%~i"
)

if defined PID (
    echo %PID% > "%PID_FILE%"
    echo Application started successfully with PID: %PID%. Log is being written to %LOG_FILE%
) else (
    echo ERROR: Could not find PID for the started process. Please check the log file '%LOG_FILE%' for errors.
)

endlocal
